package com.example.cxxdemo

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.TextView
import android.widget.Toast
import com.example.cxxdemo.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity(), View.OnClickListener {

    private lateinit var binding: ActivityMainBinding
    private var name: String = "张三"
        get() = field
        set(value) {
            field = value
        }

    external fun stringFromJNI(): String
    external fun changeName()
    external fun callAddMethod(): Int
    external fun arrayTest(cout: Int, str: String, intArray: IntArray, array: Array<String>)
    external fun putObject(person: Person, str: String)
    external fun testQuote()//测试引用
    external fun releaseQuote()//释放全局引用


    fun add(num1: Int, num2: Int): Int {
        return num1 + num2
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.tvContent.text = stringFromJNI()
        binding.sampleText.setOnClickListener(this)
        binding.tvC2Java.setOnClickListener(this)
        binding.btArrayTest.setOnClickListener(this)
        binding.btobj.setOnClickListener(this)
        binding.btcreateobj.setOnClickListener(this)
        binding.btdelete.setOnClickListener(this)
        Log.d("wyb", "原有值name: $name")
    }


    override fun onClick(v: View?) {
        v?.id.let {
            when (it) {
                R.id.sample_text -> {
                    changeName()
                    Log.i("wyb", "点击后name: $name")
                    binding.tvContent.text = name
                }
                R.id.tvC2Java -> {
                    val result = callAddMethod()
                    Log.i("wyb", "c++传递过来的值 result: ${result}")
                }
                R.id.btArrayTest -> {
                    arrayTest(4, "c++操作数组", intArray, strList)
                    Log.i("wyb", "strList: ${strList.asList().toString()}  ")
                }
                R.id.btobj -> {
                    val person = Person("王老六", 11)
                    Log.i("wyb", "修改前person: ${person.toString()}  ")
                    putObject(person, "燕子李三")
                    Log.i("wyb", "c++ 修改后 person: ${person.toString()}  ")
                }
                R.id.btcreateobj -> {
                    testQuote()
                }
                R.id.btdelete -> {
                    releaseQuote()
                }
                else -> {}
            }
        }
    }

    companion object {
        private val intArray = intArrayOf(1, 2, 3, 4)
        private val strList: Array<String> = arrayOf("张三", "李四", "王五", "赵六")

        init {

            System.loadLibrary("cxxdemo")// 默认调用:JNI_OnLoad
        }
    }
}